//
//  NetworkTools.m
//  01-BuDeJie
////
//  Created by beisheng03 on 16/11/3.
//  Copyright © 2016年 xiaomage. All rights reserved.
//

#import "NetworkTools.h"
#import <MJExtension/MJExtension.h>//JSON 对象转换工具 通用
#import "Reachability.h"
#import "BaseNavigationController.h"
@interface NetworkTools ()

@end

@implementation NetworkTools

+ (void)load{
    
    
    
    [SVProgressHUD setMaximumDismissTimeInterval:2];
    
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeCustom];
    
}

//@"http://mall.xjscvip.com/"  http://mall.xjscvip.com/mobile/
+ (instancetype)shareNetworkTools
{
    static NetworkTools *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSURL *url = [NSURL URLWithString:@"http://feidu.baonongkang.cn/index.php/api/"];
        NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
        instance = [[self alloc] initWithBaseURL:url sessionConfiguration:cfg];
//        instance = [[self alloc] initWithBaseURL:url];
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/plain", @"text/javascript",@"text/html" ,nil];
        
        instance.requestSerializer.timeoutInterval = 10;
        
        [instance setRequestSerializer:[AFHTTPRequestSerializer serializer]];
        
//        instance.responseSerializer = [AFHTTPResponseSerializer serializer];
        
//        [instance setResponseSerializer:[AFJSONResponseSerializer serializer]];
        
        
//        instance.responseSerializer = [AFXMLParserResponseSerializer serializer];//返回数据为二进制XML数据时用
        
//        instance.responseSerializer  = [AFHTTPResponseSerializer serializer];//返回数据为二进制数据时用
//
//        instance.responseSerializer = [AFJSONResponseSerializer serializer];//返回数据为二进制JSON数据时用
        
//        [instance.requestSerializer setValue:@"iPhone7" forHTTPHeaderField:@"device"];
//        [instance.requestSerializer setValue:@"9.2" forHTTPHeaderField:@"version"];
        
        
    });
    
    return instance;
    
    
}



//普通请求
- (NSURLSessionDataTask *)sendRequestWithHttpMethod:(HTTP_REQUEST_METHOD)method URLPath:(NSString *)pathStr parameters:(id)parameters completionHandler:(completionHandler)completionHandler{
    
    NSError *err = nil;
    id data = nil;
    

    
    if ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == NotReachable) {

            err = [[NSError alloc] initWithDomain:@"无网络连接..." code:400 userInfo:nil];
        
        //主线程执行回调
        dispatch_async(dispatch_get_main_queue(), ^{
            completionHandler(data, err);
        });
        
        return nil;
        
    }

    
    
    //    NotReachable = 0,
    //    ReachableViaWiFi,
    //    ReachableViaWWAN
    
    //    NetworkStatus status = [[Reachability reachabilityForInternetConnection] currentReachabilityStatus];
    
    
//    if ([parameters[@"cancel"] isEqualToString:@"1"]) {
//        
//    [parameters removeObjectForKey:@"cancel"];
//    [self.tasks makeObjectsPerformSelector:@selector(cancel)];
//
//    }
    
    //开始菊花
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    //初始化请求
    NSString *urlStr = [[NSURL URLWithString:pathStr relativeToURL:self.baseURL] absoluteString];
    
    NSString *methodStr = [self stringWithMethod:method];
    
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:methodStr URLString:urlStr parameters:parameters error:nil];
    
    __block NSURLSessionDataTask *task = nil;
    
    task = [self dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
  
//        NSLog(@"%@",error);
        //结束菊花
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        //判断结果
        NSError *err = nil;
        id data = nil;

        //如果是请求时的错误
        if(error) {
//            NSLog(@"%@",error);
            err = error;
        } else {//请求没有错
            
            if (![responseObject isKindOfClass:[NSDictionary class]]) {
                responseObject = [responseObject mj_keyValues];
            }
            
            data = responseObject;

            NSInteger resultCode = [responseObject[@"code"] integerValue];

            if(resultCode == 400) {//400表示失败
//                NSLog(@"%ld----",RequestCount);

                err = [[NSError alloc] initWithDomain:responseObject[@"message"] code:resultCode userInfo:nil];

            } else {

                data = responseObject;

            }
        }
        //主线程执行回调
        dispatch_async(dispatch_get_main_queue(), ^{
            completionHandler(data, err);
        });
    }];
    
    //发起请求任务
    [task resume];
    return task;
    
    
}



//取消请求
//[self.mgr.tasks makeObjectsPerformSelector:@selector(cancel)];



- (NSString *)stringWithMethod:(HTTP_REQUEST_METHOD)method {
    switch (method) {
        case GET_METHOD:     return @"GET";      break;
        case POST_METHOD:    return @"POST";     break;
        case HEAD_METHOD:    return @"HEAD";     break;
        case PUT_METHOD:     return @"PUT";      break;
        case PATCH_METHOD:   return @"PATCH";    break;
        case DELETE_METHOD:  return @"DELETE";   break;
        default:
            break;
    }
    return @"";
}


- (BOOL)isPhoneNumber:(NSString *)str{
    
//    NSString *pattern = @"[0][9][0-9]{9}";
    
    NSString *pattern = @"[0-9]{11}";

    
    NSRegularExpression *expres = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
    
    NSTextCheckingResult *rest = [expres firstMatchInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)];
    
//    NSLog(@"%ld",rest.range.location);
//    NSLog(@"%ld",rest.range.length);

    if (rest.range.length > 0  && rest.range.length == str.length) {
        return  YES;
    } else {
        return NO;
    }
    
}


- (BOOL)isHuHao:(NSString *)str{
    
    
    NSString *pattern = @"[0-9]{16}";
    
    NSRegularExpression *expres = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
    
    NSTextCheckingResult *rest = [expres firstMatchInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)];
    
    //    NSLog(@"%ld",rest.range.location);
    //    NSLog(@"%ld",rest.range.length);
    
    if (rest.range.length > 0  && rest.range.length == str.length) {
        return  YES;
    } else {
        return NO;
    }
    
    
    
    
}



- (BOOL)isBillNumber:(NSString *)str{
    
    
    NSString *pattern = @"[0-9]{26}";
    
    NSRegularExpression *expres = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
    
    NSTextCheckingResult *rest = [expres firstMatchInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)];
    
    //    NSLog(@"%ld",rest.range.location);
    //    NSLog(@"%ld",rest.range.length);
    
    if (rest.range.length > 0  && rest.range.length == str.length) {
        return  YES;
    } else {
        return NO;
    }
    
    
    
    
}

- (BOOL)deptNumInputShouldNumber:(NSString *)str{
    
    NSString *pattern = @"[1-9][0-9]{15,}";
    
    NSRegularExpression *expres = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
    
    NSTextCheckingResult *rest = [expres firstMatchInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)];
    
    NSLog(@"%ld",rest.range.location);
    NSLog(@"%ld",rest.range.length);
    
    if (rest.range.length > 0 && rest.range.length == str.length) {
        return  YES;
    } else {
        return NO;
    }
    
    
    
}




- (BOOL)isEmailAdress:(NSString *)str{
    
//    NSString *pattern = @"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
//
//    NSRegularExpression *expres = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
//
//    NSTextCheckingResult *rest = [expres firstMatchInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)];
//
//
//    if (rest.range.length > 0) {
//        return  YES;
//    } else {
//        return NO;
//    }
    
    
//    NSString *pattern = @"[0][9][0-9]{9}";
    NSString *pattern = @"[0-9]{11}";

    NSRegularExpression *expres = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
    
    NSTextCheckingResult *rest = [expres firstMatchInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)];

    
    if (rest.range.length > 0  && rest.range.length == str.length) {
        return  YES;
    } else {
        return NO;
    }
    
}



- (BOOL)isCaptcha:(NSString *)str{
    
    NSString *pattern = @"[0-9]{4}";
    
    NSRegularExpression *expres = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
    
    NSTextCheckingResult *rest = [expres firstMatchInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)];
    
//    NSLog(@"%ld",rest.range.location);
//    NSLog(@"%ld",rest.range.length);
    
    if (rest.range.length > 0) {
        return  YES;
    } else {
        return NO;
    }
    
}



@end
